<!-- @format -->

<template>
  <div id="reg">
    <van-form @submit="onSubmit">
      <van-uploader
        :after-read="afterRead"
        v-model="fileList"
        multiple
        max-count="1"
        style="text-algin:center"
      />
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
        autocomplete
      />
      <van-field
        v-model="nickname"
        type="nickname"
        name="nickname"
        label="昵称"
        placeholder="昵称"
        :rules="[{ required: true, message: '请填写昵称' }]"
      />
      <!-- <van-field
        v-model="icon"
        type="icon"
        name="上传头像"
        label="上传头像"
        placeholder="上传头像"
        :rules="[{ required: true, message: '请填写上传头像' }]"
      />-->
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >注册</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { apost } from "@/utils/request";
import axios from "axios";
import { Toast } from "vant";
export default {
  data() {
    return {
      fileList: [],
      username: "",
      password: "",
      nickname: "",
      icon: ""
    };
  },
  props: ["show"],
  methods: {
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
    },
    onSubmit(values) {
      if (this.fileList.length >= 1) {
        apost("http://localhost:3000/user/registered", values).then(res => {
          if (res.data.code == 200) {
            console.log(formData);
            const formData = new FormData(); // 声明一个FormData对象
            formData.append("file", this.fileList[0].file);
            axios
              .post("http://localhost:3000/user/upload", formData, {
                headers: {
                  "content-type": "multer/form-data",
                  iconUser: `${values.username}`
                }
              })
              .then(res => {
                console.log(res);
                Toast.loading({
                  message: "加载中...",
                  forbidClick: true
                });
                //把注册逐渐内侧的值传出去 让外面的框框发生改变
                setTimeout(() => {
                  values.regClicked = true;
                  this.$emit("event", values);
                }, 2000);
              });
          }
        });
      } else {
        Toast("请上传头像");
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "@sass/User/registered.scss";
</style>
